package chpt12;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class StatementTest3GetGeneratedKeys {
	//本示例演示：1.getGeneratedKeys的用法；2.从数据库读取数据并组装对象。
	//这里演示的是Statement，代码同样适用于PreparedStatement
	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/demodb?serverTimezone=Asia/Chongqing";
		String userName = "root";
		String password = "root123";
		
		
		try (Connection con = DriverManager.getConnection(url, userName, password);
				Statement stmt = con.createStatement();) {
			String sql = "insert into students(sno,name,gpa) "
					+ "values('Js-100','李某',1.65)";
			int resultNum = 0;
			resultNum = stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
			ResultSet keyrs = stmt.getGeneratedKeys();
			keyrs.next();
			int key = keyrs.getInt(1);//获取刚才新生成的主键
			System.out.println("执行："+sql);
			System.out.println(resultNum + " 条记录已经插入");
			System.out.println("你刚才插入的记录的自动生成的key是："+key);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

